package com.listeningframework.boot.commons.string;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * Jackson JSON 工具类
 */
public class JacksonUtils {
    private static final ObjectMapper mapper = initMapper();

    private static ObjectMapper initMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }

    /**
     * 获取Mapper 可以使用工具类没定义的方法
     *
     * @return ObjectMapper
     */
    public static ObjectMapper getMapper() {
        return mapper;
    }

    public static JsonNode getJsonNode(String json) {
        try {
            return mapper.readValue(json, JsonNode.class);
        } catch (Exception e) {
            throw new RuntimeException("Convert JsonNode Fail", e);
        }
    }

    /**
     * 转换JSON为对象
     *
     * @param json 输入JSON
     * @param cls 目标对象
     * @param <T> 入参泛型
     * @return T
     */
    public static <T> T convertObj(String json, Class<T> cls) {
        try {
            return mapper.readValue(json, cls);
        } catch (Exception e) {
            throw new RuntimeException("Json Convert Object Fail", e);
        }
    }

    /**
     * 抓换Json为对象List
     *
     * @param json json内容
     * @param cls  目标对象
     * @param <T> 入参泛型
     * @return List
     */
    public static <T> List<T> convertList(String json, Class<T> cls) {
        try {
            return mapper.readValue(json, new TypeReference<List<T>>() {
            });
        } catch (IOException e) {
            throw new RuntimeException("Json Convert Object List Fail", e);
        }
    }

    /**
     * 转化JSON
     *
     * @param t 要转换对象
     * @param <T> 入参泛型
     * @return String
     */
    public static <T> String toJson(T t) {
        try {
            return mapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Object Convert Json Fail", e);
        }
    }
}
